package com.yyhh.helpcall.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.button.MaterialButton;
//import com.nbsp.materialfilepicker.MaterialFilePicker;
//import com.nbsp.materialfilepicker.ui.FilePickerActivity;
import com.yyhh.helpcall.MainApplication;
import com.yyhh.helpcall.R;
import com.yyhh.helpcall.base.RecordConfig;
import com.yyhh.helpcall.http.OkHttpUtils;
import com.yyhh.helpcall.http.bean.BaseResponse;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.SpUtils;
import com.yyhh.helpcall.utils.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.rosuh.filepicker.config.FilePickerManager;

public class SettingActivity extends BaseActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        tv = findViewById(R.id.path);
        String path = SpUtils.getInstance(this).getString(SplashActivity.TARGET_PATH);
        tv.setText(path);

        MaterialButton btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new MaterialFilePicker().withActivity(SettingActivity.this).withRequestCode(201).start();
                FilePickerManager.INSTANCE
                        .from(SettingActivity.this)
                        .skipDirWhenSelect(false)
                        .enableSingleChoice()
                        .forResult(201);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 201 && resultCode == Activity.RESULT_OK) {
            try {
                List<String> paths = FilePickerManager.INSTANCE.obtainData();
                NetLog.d("onActivityResult = " + paths.toString());
                String path = paths.get(0);
//                String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
//                NetLog.d("onActivityResult = " + path);
                File file = new File(path);
                File targetFile = null;

                boolean isMatching = false;

                if (file.isDirectory()) {
                    targetFile = file;
                    isMatching=true;
                } else {
                    targetFile = file.getParentFile();
                    File[] files = targetFile.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        File file2 = files[i];
                        if (file2.getName().endsWith(".wav")
                                || file2.getName().endsWith(".m4a")
                                || file2.getName().endsWith(".amr")
                                || file2.getName().endsWith(".mp3")) {
                            isMatching = true;
                            break;
                        }
                    }
                }
//                if (file.isDirectory()) {
//                    targetFile = file;
//                } else {
//                    targetFile = file.getParentFile();
//                }
//
//                File[] files = targetFile.listFiles();
//                boolean isMatching = false;
//                for (int i = 0; i < files.length; i++) {
//                    File file2 = files[i];
//                    if (file2.getName().endsWith(".wav")
//                            || file2.getName().endsWith(".m4a")
//                            || file2.getName().endsWith(".amr")
//                            || file2.getName().endsWith(".mp3")) {
//                        isMatching = true;
//                        break;
//                    }
//                }

                if(isMatching){
                    //匹配成功
                    SpUtils.getInstance(SettingActivity.this).putString(SplashActivity.TARGET_PATH, targetFile.getAbsolutePath());
                    MainApplication.recordConfig = new RecordConfig(targetFile.getAbsolutePath(), "", "");
                    ToastUtils.show("修改成功");
                    tv.setText(targetFile.getAbsolutePath());

                    //接口上报
                    HashMap<String, String> map = new HashMap<>();
                    map.put("dir",targetFile.getAbsolutePath().replace("/storage/emulated/0",""));
                    OkHttpUtils.getInstance().getApi().upPhoneDir(map)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<BaseResponse<Object>>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(BaseResponse<Object> value) {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }else{
                    //匹配失败
                    ToastUtils.show("您选择的文件夹下面没有录音文件，请开启自动录音通话后，拨打电话生成录音文件后再选择");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}